package com.atguigu.service.impl;

import com.atguigu.dao.UserDao;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserServiceImpl
 *
 * @Author: 马伟奇
 * @CreateTime: 2021-02-23
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis是内存缓存，效率比mysql硬盘缓存
     * @return
     */


    @Override
    public List<User> findAll() {
        String key = "allUser";
        // 从redis缓存获取数据
        // redis.get("key")
        List<User> lists = (List<User>) redisTemplate.boundValueOps(key).get();
        // 判断redis里面是否有数据
        if (lists!=null){
            return lists;
        }
        // 说明redis没有数据，就需要从数据库里面获取数据
        lists = userDao.findAll();
        if (lists!=null && lists.size()>0){
            // 把数据缓存到redis
            redisTemplate.boundValueOps(key).set(lists);
        }

        return lists;
    }
}